package ee.ut.maxorato_macobo.oop.mudclient.ui;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.JTextField;

import ee.ut.maxorato_macobo.oop.mudclient.network.ClientIoManager;

public class ClientCmdField extends JTextField implements KeyListener {
	private static final long serialVersionUID = -1451441272047409282L;
	private ArrayList<String> commandHistory;
	private int at;

	public ClientCmdField() {
		super();
		
		addKeyListener(this);
		commandHistory = new ArrayList<String>();
		at = -1;
		setFocusTraversalKeysEnabled(false);
		// Always retain focus
		addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e) {
				JTextField target = (JTextField)e.getSource();
				target.requestFocusInWindow();
			}
		});
	}

	@Override
	public void keyPressed(KeyEvent e) {
		// on tab press, display commands.
		if (e.getKeyCode() == KeyEvent.VK_TAB) 
			ClientIoManager.sendOutput("cmds " + getText() + "\n");
		// remember previous input
		if (e.getKeyCode() == KeyEvent.VK_UP && commandHistory.size() > 0) {
			if (at == -1)
				at = commandHistory.size();
			if (at > 0) 
				at--;
			setText(commandHistory.get(at));
			
		}
		else if (e.getKeyCode() == KeyEvent.VK_DOWN && commandHistory.size() > 0) {
			if (at > -1 && at < commandHistory.size() - 1) {
				at++;
				setText(commandHistory.get(at));
			}
			else if (at != -1) {
				setText("");
				at = -1;
			}
		}
		else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			ClientIoManager.gotInput(getText() + "\n");
			ClientIoManager.sendOutput(getText() + "\n");
			commandHistory.add(getText());
			setText("");
			at = -1;
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {

	}

	@Override
	public void keyTyped(KeyEvent e) {

	}
}
